<template>
    <div class="material-select">
        <el-upload
            class="avatar-uploader"
            :class="{ 'hide-upload-btn': photoHide, 'upload-btn': showbtn }"
            v-if="!disabled || fileList.length != 0"
            v-model:file-list="fileList"
            action="#"
            :http-request="uploadAction"
            list-type="picture-card"
            :limit="limit"
            :before-upload="beforeAvatarUpload"
            :on-change="fileChange"
            :show-file-list="true"
            :auto-upload="false"
            :disabled="disabled"
        >
            <el-button type="primary" size="small" v-if="showbtn" :disabled="disabled"
                >上传</el-button
            >
            <el-icon class="avatar-uploader-icon" v-else>
                <Plus />
            </el-icon>
            <template #file="{ file }" v-if="false">
                <div>
                    <img v-if="img" class="el-upload-list__item-thumbnail" :src="file.url" alt />
                    <img
                        v-else
                        class="el-upload-list__item-thumbnail"
                        src="../../assets/images/icon_folder.png"
                        alt
                    />
                    <el-tooltip class="box-item" effect="dark" :content="file.name" placement="top">
                        <span class="el-upload-list__item-actions">
                            <span
                                class="el-upload-list__item-preview"
                                v-if="!img"
                                @click="handlePictureCardPreview(file, 2)"
                            >
                                <el-icon>
                                    <Download />
                                </el-icon>
                            </span>
                            <span
                                class="el-upload-list__item-preview"
                                v-if="img"
                                @click="handlePictureCardPreview(file)"
                            >
                                <el-icon>
                                    <zoom-in />
                                </el-icon>
                            </span>
                            <span
                                class="el-upload-list__item-delete"
                                v-if="!disabled"
                                @click="handleRemove(file)"
                            >
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </el-tooltip>
                </div>
            </template>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img w-full class="imgs" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script lang="ts">
import Draggable from 'vuedraggable'
import Popup from '@/components/popup/index.vue'
import {
    uploadImage,
    uploadAttachment,
    //新添加
    downloadFile
} from '@/api/upload/list'
import feedback from '@/utils/feedback'
import FileItem from './file.vue'
import Material from './index.vue'
import Preview from './preview.vue'
import { ElMessageBox } from 'element-plus'
export default defineComponent({
    components: {
        Popup,
        Draggable,
        FileItem,
        Material,
        Preview
    },
    props: {
        // 显示状态
        img: {
            type: Boolean,
            default: true
        },
        modelValue: {
            type: [String, Array],
            default: () => []
        },
        // 文件类型
        type: {
            type: String,
            default: 'image'
        },
        // 选择器尺寸
        size: {
            type: String,
            default: '100px'
        },
        // 文件尺寸
        fileSize: {
            type: String,
            default: '100px'
        },
        // 选择数量限制
        limit: {
            type: Number,
            default: 1
        },
        // 禁用选择
        disabled: {
            type: Boolean,
            default: false
        },
        // 隐藏上传框*(目前在富文本中使用到)
        hiddenUpload: {
            type: Boolean,
            default: false
        },
        // 上传按钮显示
        photoHide: {
            type: Boolean,
            default: false
        },
        // 上传类型
        typeshow: {
            type: Boolean,
            default: false
        },
        showbtn: {
            type: Boolean,
            default: false
        }
    },
    setup(props, { emit }) {
        const { modelValue } = toRefs(props)
        const type = ref(1)
        const imgList = ref<any>([])
        const dialogImageUrl = ref('')
        // 文件改变
        const fileChange = (file: any, resfileList: any) => {
            if (resfileList) {
                fileList.value = resfileList
                if (fileList.value[fileList.value.length - 1].raw) {
                    uploadAction(fileList.value[fileList.value.length - 1].raw)
                }
            }
        }
        const fileList = ref<any[]>([])
        const uptu = ref()
        const beforeAvatarUpload = (rawFile: any) => {
            if (!props.typeshow) {
                const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/ico']
                if (type.indexOf(rawFile.type) === -1) {
                    feedback.msgError('图片格式不支持')
                    return false
                } else if (rawFile.size / 1024 / 1024 > 15) {
                    feedback.msgError('图片大小不能超过15MB')
                    return false
                }
                return (uptu.value = true)
            } else {
                const type = ['pdf', 'doc', 'docx', 'ppt', 'xls', 'xlsx', 'zip', 'rar']
                if (type.indexOf(rawFile.name.split('.')[1]) === -1) {
                    feedback.msgError('附件格式不支持')
                    return false
                } else if (rawFile.size / 1024 / 1024 > 15) {
                    feedback.msgError('附件大小不能超过15MB')
                    return false
                }
                return (uptu.value = true)
            }
        }
        const uploadAction = (option: any) => {
            const aa = beforeAvatarUpload(option)
            if (!aa) {
                return fileList.value.splice(fileList.value.length - 1, 1)
            } else {
                const param = new FormData()
                param.append('file', option)
                if (!props.typeshow) {
                    uploadImage(param).then((res: any) => {
                        if (res && res.cid == 0) {
                            const data = {
                                name: res.name,
                                url: res.uri
                            }
                            imgList.value.push(data)
                            feedback.msgSuccess('上传成功')
                        }
                    })
                } else {
                    uploadAttachment(param).then((res: any) => {
                        if (res && res.cid == 0) {
                            let data = {
                                id: res.id,
                                name: res.name,
                                url: res.uri
                            }
                            if (props.showbtn) {
                                data = {
                                    id: res.id,
                                    attach_url: res.url,
                                    attache_name: res.name,
                                    remark: ''
                                }
                            }
                            imgList.value.push(data)
                            feedback.msgSuccess('上传成功')
                        }
                    })
                }
            }
        }
        // 预览图片
        const handlePictureCardPreview = (file: any, type: any) => {
            if (type == 2) {
                //调用下载
                downloadFile(file.url, file.name)
            } else {
                // downloadFile(file.url,file.name)
                dialogImageUrl.value = file.url
                dialogVisible.value = true
            }
        }
        const dialogVisible = ref(false)
        // 移除图片
        const handleRemove = (file: any, rawFile: any) => {
            ElMessageBox.confirm('文件删除后，将无法恢复', {
                title: '温馨提示',
                confirmButtonText: '确认',
                cancelButtonText: '再想一想'
            })
                .then(() => {
                    type.value = 2
                    const list = fileList.value
                    for (const i in list) {
                        if (list[i].uid == file.uid) {
                            list.splice(i, 1)
                            imgList.value.splice(i, 1)
                        }
                    }
                    fileList.value = list
                })
                .catch(() => {})
        }
        const popupRef = ref<InstanceType<typeof Popup>>()
        const materialRef = ref<InstanceType<typeof Material>>()
        const previewUrl = ref('')
        watch(
            modelValue,
            (newValue) => {
                fileList.value = []
                imgList.value = []
                for (let i = 0; i < newValue.length; i++) {
                    fileList.value.push({
                        url: newValue[i].url,
                        name: newValue[i].name || '无数据'
                        // "url": newValue[i]
                        // "name": "默认文件名"
                    })
                }
                imgList.value = newValue
            },
            {
                immediate: true
            }
        )
        watch(
            imgList.value,
            (newValue) => {
                emit('update:modelValue', newValue)
            },
            {
                deep: true
            }
        )
        return {
            popupRef,
            materialRef,
            fileList,
            previewUrl,
            beforeAvatarUpload,
            uploadAction,
            handleRemove,
            handlePictureCardPreview,
            dialogVisible,
            fileChange,
            dialogImageUrl
        }
    }
})
</script>

<style scoped lang="scss">
::v-deep .el-upload--picture-card {
    width: 50px;
    height: 50px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
}

::v-deep .el-upload--picture-card {
    background-color: #fff;
}

::v-deep .hide-upload-btn {
    .el-upload--picture-card {
        display: none;
    }
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-actions {
    font-size: 16px;
}

.imgs {
    width: 100%;
    height: auto;
}
.upload-btn {
    width: 48px;
    height: 24px;
}
::v-deep .upload-btn .el-upload--picture-card {
    width: 48px;
    height: 24px;
}

::v-deep .upload-btn .el-upload-list--picture-card .el-upload-list__item {
    display: none;
}
</style>
